package com.link.play.fit.ai.ui.main.saveFood.details

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.CollectFoodInfoData
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.bean.ReqCollectFoodData
import com.link.play.fit.ai.bean.ReqData
import com.link.play.fit.ai.databinding.FixResultLayoutBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.utils.ScreenUtil.Companion.dpToPx
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import kotlin.math.roundToInt


class FixResultAc : BaseActivity<FixResultLayoutBinding>(FixResultLayoutBinding::inflate) {
    private var hasText = false
    private var animator: ValueAnimator? = null
    private var collectFoodInfoData: CollectFoodInfoData?=null
    private var mType = ""
    private var dataR: RecentlyEatenData?=null

    val viewModel: FixFoodViewmModel by lazy {
        ViewModelProvider(this)[FixFoodViewmModel::class.java]
    }

    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mType = intent.getStringExtra("type")?:""
        if(mType == "saveFood"){
            collectFoodInfoData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getSerializableExtra("foodBean",CollectFoodInfoData::class.java)
            } else {
                intent.getSerializableExtra("foodBean")as CollectFoodInfoData?
            }
        }else{
            dataR = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getSerializableExtra("recentlyEatenData",RecentlyEatenData::class.java)
            } else {
                intent.getSerializableExtra("recentlyEatenData")as RecentlyEatenData?
            }
        }

        initData()
        initListener()
        observerRequest()

    }

    private fun initListener() {
        with(binding) {
            backImage.setOnClickListener {
                finish()
            }
            updateLayout.setOnClickListener {
                if(loadImage.isVisible) return@setOnClickListener
                if (!hasText) return@setOnClickListener
                loadImage.isVisible = true
                updateText.isVisible = false
                startAi()
                if(mType == "saveFood"){
                    collectFoodInfoData?.apply {
                        description = fixEdit.text.toString()
                        val foodData = ReqData()
                        foodData.foodData = this
                        foodData.issue = description
                        viewModel.byDescribe(ReqCollectFoodData().apply { data=foodData })
                    }
                }else{
                    dataR?.let {
                        collectFoodInfoData = CollectFoodInfoData().apply {
                            name = it.foodName?:""
                            calories = it.caloriesDaily.toDouble()
                            carbs = it.carbsDaily.toDouble()
                            protein = it.proteinDaily.toDouble()
                            fats = it.fatsDaily.toDouble()
                            servings = it.servings
                            img = it.img
                            type = it.type
                            description = it.describe
                            timeMillisecond = it.createTime
                        }
                        val foodData = ReqData()
                        foodData.foodData = collectFoodInfoData
                        foodData.issue = fixEdit.text.toString()
                        viewModel.byDescribe(ReqCollectFoodData().apply { data=foodData })
                        "collectData  $collectFoodInfoData".d()

                    }
                }

            }

        }
    }

    private fun initData() {
        binding.fixEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            @SuppressLint("UseCompatLoadingForDrawables")
            override fun afterTextChanged(s: Editable) {
                hasText = s.toString().trim { it <= ' ' }.isNotEmpty()
                binding.updateLayout.background =
                    (if (hasText) getDrawable(R.drawable.bg_a_style_05_green_full_r360) else getDrawable(
                        R.drawable.bg_a_style_05_gry_full_r360
                    ))
            }
        })

    }

    private fun observerRequest() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.desFixLiveBean.collect { bean ->
                    if (bean.status == -1) return@collect
                    "response foodInfoLiveData  $bean".d()

                    binding.loadImage.isVisible = false
                    binding.updateText.isVisible = true
                    animator?.cancel()

                    bean.fixByIssueBean?.let {
                        if(mType == "saveFood"){
                            goToAc(FixResultDetailAc::class.java){
                                putExtra("foodBean",collectFoodInfoData)
                                putExtra("fixBean",bean.fixByIssueBean)
                            }
                            EventBus.getDefault().post("finishFoodDetail")
                        }else{

                            dataR?.apply {
                                foodName = it.name
                                it.calories?.let { k->
                                    caloriesDaily = k.roundToInt()
                                }
                                it.protein?.let { k->
                                    proteinDaily = k.roundToInt()
                                }
                                it.carbs?.let { k->
                                    carbsDaily = k.roundToInt()
                                }
                                it.fats?.let { k->
                                    fatsDaily = k.roundToInt()
                                }
                                it.servings?.let { k->
                                    servings = k
                                }
                            }
                            setResult(Activity.RESULT_OK, Intent().apply {
                                putExtra("recentlyEatenData", dataR)
                            })
                        }
                        finish()
                    }
                }
            }
        }

    }

    private fun startAi() {
        // 创建 ValueAnimator
        animator = ValueAnimator.ofFloat(0f, 360f)
        animator?.setDuration(2000) // 动画时长 2 秒
        animator?.repeatCount = ValueAnimator.INFINITE // 无限重复
        animator?.repeatMode = ValueAnimator.RESTART // 重复模式

        animator?.addUpdateListener { animation ->
            val angle = animation.animatedValue as Float
            binding.loadImage.setStartAngle(angle) // 更新起始角度
        }

        animator?.start() // 启动动画

    }

    override fun onDestroy() {
        super.onDestroy()
        animator?.cancel()
    }
}